<html>
  <head><title>Chris Moghbel CS 143 Project B</title></head>
  <body>
    <p>Type a SQL query in the following box:</p>
    <?php $query = $_GET['query']; ?>
    <form  method="GET">
      <textarea name="query" cols="60" rows="8"><?php echo $query; ?></textarea>
      <input type="submit" value="Submit">
    </form>
    <?php
      if ($query)
      {
        $db_connection = mysql_connect("localhost", "cs143", "");
        mysql_select_db("CS143", $db_connection);
        if (!(substr($query, 0, strlen("SELECT")) === "SELECT"
            || substr($query, 0, strlen("SHOW")) === "SHOW"))
        {
          echo "<p>Sorry, only SELECT and SHOW queries allowed!</p>\n";
        }
        else
        {
          $rs = mysql_query($query, $db_connection);
          if (!$rs)
          {
            echo "<p>There was an error with your SQL query. Did you use a query other than SELECT or SHOW?</p>\n";
          }
          else
          {
            echo "<h3>Results from MySQL:</h3>\n\n";
            echo "<table border=1 cellspacing=1 cellpadding=1>\n";
            echo "<tr align=center>";
            for ($i = 0; $i < mysql_num_fields($rs); ++$i)
            {
              $columnName = mysql_field_name($rs, $i);
              echo "<td><b>$columnName</b></td>";
            }
            echo "</tr>\n";
            while ($row = mysql_fetch_row($rs))
            {
              echo "<tr align=center>";
              foreach ($row as $value)
              {
                if (!$value)
                {
                  $value = "N/A";
                }
                echo "<td>$value</td>";
              }
              echo "</tr>\n";
            }
            echo "</table><br />\n";
          }
          mysql_close($db_connection);
        }
      }
    ?>
  </body>
</html>
